/**
 * 
 */
package arisufascion.com.activity;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.lib.recaptcha.ReCaptcha;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import arisufascion.com.AbstractActivity;
import arisufascion.com.R;
import arisufascion.com.capcha.Captcha;
import arisufascion.com.constant.WriteLog;
import arisufascion.com.network.RequestTask;

/**
 * @author Kelvin
 * 
 */
public class ActivityContactUs extends AbstractActivity implements
		ReCaptcha.OnShowChallengeListener, ReCaptcha.OnVerifyAnswerListener {
	private static final String PUBLIC_KEY = "6LeCjO8SAAAAAK8H6jDaPG1Zm6Ue_A-9TrUeqn6V";
	private static final String PRIVATE_KEY = "6LeCjO8SAAAAAE0DPCdrKvr0jht0QYvFu1y2loat";

	private TextView ans;
	private EditText editanswer;
	private Captcha c;
	private TextView txt_message_success;
	private boolean isLoading = true;
	private ProgressDialog dialog;
	private EditText editTextName, editTextEmail, editTextContact,
			editTextSubject, editTextMessage, editTextCapcha;
	private Button btnSend;
	private ReCaptcha reCaptcha;
	private String name, email, contact, subject, message, capcha;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact);
		initView();
		reCaptcha = (ReCaptcha) findViewById(R.id.recaptcha);

		txt_message_success = (TextView) findViewById(R.id.txt_message_success);

		findViewById(R.id.btn_menu).setOnClickListener(onClick);
		findViewById(R.id.btn_privacy).setOnClickListener(onClick);
		findViewById(R.id.btn_wholesale).setOnClickListener(onClick);
		findViewById(R.id.btn_shipping).setOnClickListener(onClick);

		this.showChallenge();

		findViewById(R.id.btnSend).setOnClickListener(onClickEvent);

		editTextName.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					self.getWindow()
							.setSoftInputMode(
									WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
				} else {
					InputMethodManager imm = (InputMethodManager) self
							.getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(editTextName.getWindowToken(),
							0);
				}

			}
		});

	}

	public void initView() {
		this.findViewById(R.id.reload).setOnClickListener(onClickEvent);
		editTextName = (EditText) findViewById(R.id.editTextName);
		editTextEmail = (EditText) findViewById(R.id.editTextEmail);
		editTextContact = (EditText) findViewById(R.id.editTextContact);
		editTextSubject = (EditText) findViewById(R.id.editTextSubject);
		editTextMessage = (EditText) findViewById(R.id.editTextMessage);
		editTextCapcha = (EditText) findViewById(R.id.editTextCapcha);
		btnSend = (Button) findViewById(R.id.btnSend);
		btnSend.setOnClickListener(onClick);

		editTextEmail.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (editTextEmail.getText().toString()
						.matches("[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+")
						&& s.length() > 0) {
					// editTextEmail.setText("valid email");
					// Toast.makeText(ActivityContactUs.this,
					// "Mail valid", Toast.LENGTH_SHORT)
					// .show();
				} else {
					// editTextEmail.setText("invalid email");
					// Toast.makeText(ActivityContactUs.this,
					// "Mail is not valid", Toast.LENGTH_SHORT)
					// .show();

					Spanned Mail_is_not_Valid = Html
							.fromHtml("<font color='red'>Mail is not Valid"
									+ "</font>");
					editTextEmail.setError(Mail_is_not_Valid);
					return;
				}
			}
		});

	}

	boolean isEmailValid(CharSequence email) {
		return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
	}

	public OnClickListener onClickEvent = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnSend:

				name = editTextName.getText().toString();
				email = editTextEmail.getText().toString();
				contact = editTextContact.getText().toString();
				subject = editTextSubject.getText().toString();
				message = editTextMessage.getText().toString();
				capcha = editTextCapcha.getText().toString();
				Spanned error_msg = Html
						.fromHtml("<font color='red'>Invalid Input" + "</font>");
				Spanned error_name = Html
						.fromHtml("<font color='red'>Please type your full name"
								+ "</font>");
				if (name.length() < 1) {
					editTextName.setError(error_name);
					editTextName.requestFocus();
					return;
				}
				if (email.length() > 0) {
					if (!isEmailValid(editTextEmail.getText())) {
						Spanned Mail_is_not_Valid = Html
								.fromHtml("<font color='red'>Mail is not Valid"
										+ "</font>");
						editTextEmail.setError(Mail_is_not_Valid);
						editTextEmail.requestFocus();
						return;
					}
				} else {
					Spanned Mail_is_not_Valid = Html
							.fromHtml("<font color='red'>Mail is not Valid"
									+ "</font>");
					editTextEmail.setError(Mail_is_not_Valid);
					editTextEmail.requestFocus();
					return;
				}

				if (subject.length() < 1) {
					editTextSubject.setError(error_msg);
					editTextSubject.requestFocus();
					return;
				}
				if (message.length() < 1) {
					editTextMessage.setError(error_msg);
					editTextMessage.requestFocus();
					return;
				}

				verifyAnswer(error_msg);

				new submitContact().execute();

				break;
			case R.id.reload:
				showChallenge();
				break;

			default:
				break;
			}
		}
	};

	public class submitContact extends AsyncTask<Void, Void, Boolean> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// Show Dialog
			if (isLoading) {
				dialog = new ProgressDialog(getParent());
				dialog.setMessage("Fetching data...");
				dialog.setCancelable(true);
				dialog.show();
				isLoading = false;
			}

		}

		@Override
		protected Boolean doInBackground(Void... params) {

			try {
				String json = RequestTask.createContact(self, name, email,
						contact, subject, message);

				JSONObject jsonObj = new JSONObject(json);

				boolean success = jsonObj.getBoolean("data");
				WriteLog.d(TAG, jsonObj.getString("data"));
				return success;
			} catch (Exception e) {
				// TODO: handle exception
			}
			return null;

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			// Dismiss Dialog
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			if (result) {
				showChallenge();
				resetAllField();
				txt_message_success.setVisibility(VISIBLE);
			}
		}

	}

	private void showChallenge() {
		// Displays a progress bar while downloading CAPTCHA
		this.reCaptcha.setVisibility(View.VISIBLE);

		this.reCaptcha.showChallengeAsync(ActivityContactUs.PUBLIC_KEY, this);
	}

	private void verifyAnswer(Spanned error) {
		if (TextUtils.isEmpty(this.editTextCapcha.getText())) {
			editTextCapcha.setError(error);
			editTextCapcha.requestFocus();
			return;
		} else {
			// Displays a progress bar while submitting the answer for
			// verification
			// this.progress.setVisibility(View.VISIBLE);
			this.reCaptcha.verifyAnswerAsync(ActivityContactUs.PRIVATE_KEY,
					this.editTextCapcha.getText().toString(), this);
		}
	}

	public void resetAllField() {
		editTextName.setText("");
		editTextEmail.setText("");
		editTextContact.setText("");
		editTextSubject.setText("");
		editTextMessage.setText("");
		editTextCapcha.setText("");
	}

	@Override
	public void onAnswerVerified(boolean success) {
		if (success) {
			Toast.makeText(this, R.string.verification_success,
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, R.string.verification_failed,
					Toast.LENGTH_SHORT).show();
		}

		// (Optional) Shows the next CAPTCHA
		// this.showChallenge();

	}

	@Override
	public void onChallengeShown(final boolean shown) {

		if (shown) {
			// If a CAPTCHA is shown successfully, displays it for the user to
			// enter the words
			this.reCaptcha.setVisibility(View.VISIBLE);
		} else {
			Toast.makeText(this, R.string.show_error, Toast.LENGTH_SHORT)
					.show();
		}
	}
}
